package com.handpay.zztong.hp;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HPLog;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.PurchaseStatus;
import com.handpay.zztong.hp.bean.UserAccount;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.ui.DialogFactory;
import com.handpay.zztong.hp.ui.MoneyEdit;

import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

public class RedeemFundActivity extends ZZTongActivity {

	private TextView redeemDate,estimateDate;
	private TextView CRamount,CARamount;
	private Button redeemButton;
	private String userRedeemAmount;
	private MoneyEdit inputRedeemAmount;
	private GfFoundIndex fundIndex = new GfFoundIndex();
	private String [] flowDesc;
	private UserAccount  users = null;
	private static final int REQ_REDEEM_CODE = 104;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.redeem_fund);
		super.onCreate(savedInstanceState);
		getRedeemData();
		initView();
	}
	
	private void getRedeemData(){
		 
		if(getIntent() != null){
			  byte data[] = getIntent().getByteArrayExtra("data");
			  if(null != data){
				  LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
			 	    LuaTable paymentWorkFlowDesc = (LuaTable) luaTable.rawget("paymentWorkFlowDesc");//arry<String>
			 	    flowDesc = fundIndex.getStringArrayFromTable(paymentWorkFlowDesc);
			 		LuaTable userActInfo = (LuaTable) luaTable.rawget("userActInfo");
		   	 		HPLog.i("PurchaseFundActivity", "userActInfo：" + userActInfo);
			 		users = GfFoundIndex.getUserAccount(userActInfo);		
			  }
		}	
}
	/**
	 * 初始化控件
	 */
	public void initView(){
		
//		findViewById(R.id.left_bar).setOnClickListener(this);
//		((TextView)findViewById(R.id.title)).setText(this.getString(R.string.redeemFund));
		
		redeemDate = (TextView)findViewById(R.id.redeemDate);
		estimateDate = (TextView)findViewById(R.id.estimateRedeemDate);		
		CRamount = (TextView)findViewById(R.id.currentRedeemAmount);
		CARamount = (TextView)findViewById(R.id.availableRedeemAmount);

		inputRedeemAmount = (MoneyEdit)findViewById(R.id.inputRedeemAmount);
		redeemButton = (Button)findViewById(R.id.redeem_bt);
		redeemButton.setOnClickListener(this);
		setControlValue();
	}
	
	/**
	 * 
	 */
	private void setControlValue(){
		redeemDate.setText(flowDesc[0].replace("|", "\n"));
		estimateDate.setText(flowDesc[1].replace("|", "\n"));
		HPLog.i("RedeemFundActivity------------", "users.getNewnet()：" + users.getNewnet());
 		HPLog.i("RedeemFundActivity----------------", "getAvaliableRetrun：" + users.getAvaliableRetrun());
		CRamount.setText(CommonUtils.formatMoneyDouble(Double.parseDouble(users.getNewnet()+"")/100));
		CARamount.setText(CommonUtils.formatMoneyDouble(Double.parseDouble(users.getAvaliableRetrun()+"")/100));
		inputRedeemAmount.setText("");
	}

	/**
	 * 获取申请赎回
	 */
	private void getRedemption(double amountApply){
		 Hashtable<String, String> params = new Hashtable<String, String>();
		 String amountString = "" + Math.round(amountApply * 100);
	     params.put("amount", SecureManager.getInstance().des(amountString, 1, null));
	     params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
	     params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
	     params.put(BaseProtocolKey.PRODUCTCODE, "HLC");//基金类型
	     this.doPost(this, Do_ZztRedemption, params);
	}

	@Override
	protected boolean isShownTopBar() {
		return true;
	}

	@Override
	protected boolean isShownTabs() {
		return false;
	}
	private boolean isInputAmount(){
		userRedeemAmount = inputRedeemAmount.getText().toString();
		if(TextUtils.isEmpty(userRedeemAmount)){
			DialogFactory.showAlertDialog(this, getString(R.string.tip),
                    getString(R.string.please_inputRedeemAmount), true);
			return false;
		}
		if(".".equals(userRedeemAmount)){
			DialogFactory.showAlertDialog(this, getString(R.string.tip),
                    getString(R.string.please_inputRedeemAmount), true);
			return false;
		}
		double redeemAmount = Double.parseDouble(userRedeemAmount);
		if(0 >= redeemAmount){
			DialogFactory.showAlertDialog(this, getString(R.string.tip),
                    getString(R.string.please_inputRedeemAmount), true);
			return false;
		}
		if(users.getAvaliableRetrun()  < redeemAmount* 100){
			DialogFactory.showAlertDialog(this, getString(R.string.tip),
                    getString(R.string.please_inputAmount_redeem_larger), true);
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		if (v != null) {
            int i = v.getId();
            if (i == R.id.tv_update_phone) {
            	

            } else if (i == R.id.redeem_bt) {
            	
            	if(isInputAmount()){            		
            		String mUserRedeemAmount = "您本次赎回金额为：" + CommonUtils.formatMoneyDouble(Double.parseDouble(userRedeemAmount)) + "元";
            		showAlertDialog(this, getString(R.string.tip),mUserRedeemAmount,true,"确认",new DialogInterface.OnClickListener() {
					
            			@Override
            			public void onClick(DialogInterface dialog, int which) {
            				double mAmount = Double.parseDouble(userRedeemAmount);
            				getRedemption(mAmount);
							dialog.dismiss();
            			}
            		},"取消",new DialogInterface.OnClickListener() {
					
            			@Override
            			public void onClick(DialogInterface dialog, int which) {
            				dialog.dismiss();
            			}
            		},null,null);	
            	}	
            }
		}
	}
	@Override
	public boolean netResponse(String action, Hashtable<String, Object> resp,
			boolean showAlert, OnClickListener on) {
		boolean result = super.netResponse(action, resp, showAlert,on);
		if (result == true) 
	    {
	            this.setResult(Activity.RESULT_CANCELED);
	            this.closeProgressDialog();
	            return true;
	    }
		if(Do_ZztRedemption.equals(action)){
			byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
			if(null != data){
				LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
	   	 	    LuaTable redemptionStatus = (LuaTable)luaTable.rawget("purchaseStatus");
	   	 	    if(redemptionStatus !=null && redemptionStatus instanceof LuaTable){
	   	 		HPLog.i("redemptionStatus", "redemptionStatus：" + redemptionStatus);
	   	 	    PurchaseStatus status = PurchaseStatus.generatePurchaseStatus(redemptionStatus);
		   	 	    if(status != null){
			   	 		Intent it = new Intent(this,RedemptionResult.class);
				 		it.putExtra("purchaseStatus", status);
				 		startActivityForResult(it, REQ_REDEEM_CODE);
		   	 	    }
	   	 		}else{
	   	 			String responseCode = (String) luaTable.rawget("responseCode");
	   	 			String errorMessage = (String) luaTable.rawget("errMessage");
	   	 			System.out.println("fail"+responseCode+":"+errorMessage);
	   	 			showAlertDialog(this, getString(R.string.tip),errorMessage, true,null);
	   	 		}
			}	 		
		} else if(Do_ZztRedemptionInfo.equals(action)){
			byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
				if(null != data){
					LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
					LuaTable paymentWorkFlowDesc = (LuaTable) luaTable.rawget("paymentWorkFlowDesc");//arry<String>
					flowDesc = fundIndex.getStringArrayFromTable(paymentWorkFlowDesc);
					LuaTable userActInfo = (LuaTable) luaTable.rawget("userActInfo");
	   	 			HPLog.i("PurchaseFundActivity", "userActInfo：" + userActInfo);
	   	 			if(null != userActInfo){
	   	 				users = GfFoundIndex.getUserAccount(userActInfo);
	   	 				setControlValue();
	   	 			}
			}			
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == REQ_REDEEM_CODE && resultCode == REQUEST_REDEEM_CODE){
			 Hashtable<String, String> params = new Hashtable<String, String>();
		     params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
		     params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
		     params.put(BaseProtocolKey.PRODUCTCODE, "HLC"); 
		     this.doPost(this, Do_ZztRedemptionInfo, params);
		}
	}
	
//    @Override
//	public void onLeftBar(View v) {
//		setResult(REQUEST_APPLYPR_CODE_TIP);
//		goBack();
//	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK){
			setResult(REQUEST_APPLYPR_CODE_TIP);
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public ActionBar getActivityActionBar() {
		setResult(REQUEST_APPLYPR_CODE_TIP);
		return new ActionBar(this.getString(R.string.redeemFund),true);
	}
	
}
